from django.utils import timezone  # 修改时区导入
from django.contrib import admin
from django.utils.html import format_html
from .models import (
    DjChefWallet, DjChefBankCard,
    DjWithdrawal, DjWalletTransaction
)

@admin.register(DjChefWallet)
class DjChefWalletAdmin(admin.ModelAdmin):
    """厨师钱包管理"""
    list_display = (
        'id', 'chef_link', 'balance', 'frozen_amount',
        'available_balance_display', 'total_earned', 'total_withdrawn',
        'is_locked', 'updated_at', 'action_buttons'  # 增加操作列
    )
    list_filter = ('is_locked',)
    search_fields = ('chef__user__username', 'chef__name')
    readonly_fields = ('created_at', 'updated_at', 'last_withdraw_at')
    fieldsets = (
        ('关联信息', {
            'fields': ('chef',)
        }),
        ('余额信息', {
            'fields': ('balance', 'frozen_amount', 'total_earned', 'total_withdrawn')
        }),
        ('提现限制', {
            'fields': (
                'daily_withdraw_limit', 'min_withdraw_amount',
                'withdraw_fee_rate', 'withdraw_count_today', 'last_withdraw_at'
            )
        }),
        ('安全设置', {
            'fields': ('security_password', 'is_locked')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at')
        })
    )

    def chef_link(self, obj):
        """生成厨师链接"""
        return format_html(
            '<a href="/admin/chefs/djchef/{}/">{}</a>',
            obj.chef.id,
            f"{obj.chef.real_name}({obj.chef.id})"
        )
    chef_link.short_description = '关联厨师'

    def available_balance_display(self, obj):
        """显示可用余额（余额-冻结金额）"""
        return obj.available_balance()
    available_balance_display.short_description = '可用余额'

    def action_buttons(self, obj):
        """生成操作按钮"""
        return format_html(
            '<a class="button" href="/admin/payments/djchefwallet/{}/change/">编辑</a>&nbsp;'
            '<a class="button" href="/admin/payments/djchefwallet/{}/delete/">删除</a>',
            obj.id, obj.id
        )
    action_buttons.short_description = '操作'


class DjChefBankCardInline(admin.TabularInline):
    """银行卡内联管理（在钱包详情页展示）"""
    model = DjChefBankCard
    extra = 0
    readonly_fields = ('last_four', 'created_at', 'updated_at')
    fields = (
        'bank_name', 'bank_code', 'last_four', 'card_type',
        'card_holder', 'expire_date', 'is_default', 'is_valid'
    )
    can_delete = False  # 防止误删，如需删除可在单独页面操作


@admin.register(DjChefBankCard)
class DjChefBankCardAdmin(admin.ModelAdmin):
    """厨师银行卡管理"""
    list_display = (
        'id', 'wallet_link', 'bank_name', 'last_four',
        'card_type', 'card_holder', 'is_default', 'is_valid', 'action_buttons'  # 增加操作列
    )
    list_filter = ('card_type', 'is_default', 'is_valid', 'bank_code')
    search_fields = ('card_holder', 'last_four', 'bank_name')
    readonly_fields = ('last_four', 'created_at', 'updated_at')
    fieldsets = (
        ('关联信息', {
            'fields': ('wallet', 'chef_id')
        }),
        ('卡片信息', {
            'fields': (
                'bank_name', 'bank_code', 'card_number', 'last_four',
                'card_type', 'card_holder', 'expire_date'
            )
        }),
        ('状态信息', {
            'fields': ('is_default', 'is_valid')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at')
        })
    )

    def wallet_link(self, obj):
        """生成钱包链接"""
        return format_html(
            '<a href="/admin/payments/djchefwallet/{}/">{}</a>',
            obj.wallet.id,
            f"钱包({obj.wallet.chef.real_name})"
        )
    wallet_link.short_description = '关联钱包'

    def action_buttons(self, obj):
        """生成操作按钮"""
        return format_html(
            '<a class="button" href="/admin/payments/djchefbankcard/{}/change/">编辑</a>&nbsp;'
            '<a class="button" href="/admin/payments/djchefbankcard/{}/delete/">删除</a>',
            obj.id, obj.id
        )
    action_buttons.short_description = '操作'


@admin.register(DjWithdrawal)
class DjWithdrawalAdmin(admin.ModelAdmin):
    """提现记录管理"""
    list_display = (
        'id', 'wallet_link', 'chef_id', 'amount', 'fee',
        'method', 'status', 'account_info', 'requested_at', 'processed_at', 'action_buttons'  # 增加操作列
    )
    list_filter = ('method', 'status', 'requested_at')
    search_fields = ('transaction_id', 'account_number', 'chef_id')
    # 移除或注释掉date_hierarchy以避免时区错误
    # date_hierarchy = 'requested_at'
    readonly_fields = ('requested_at', 'processed_at')
    action_buttons = ['mark_as_completed', 'mark_as_failed']

    def wallet_link(self, obj):
        """生成钱包链接"""
        return format_html(
            '<a href="/admin/payments/djchefwallet/{}/">{}</a>',
            obj.wallet.id,
            f"钱包({obj.wallet.chef.real_name})"
        )
    wallet_link.short_description = '关联钱包'

    def account_info(self, obj):
        """显示账户信息（脱敏）"""
        return f"{obj.account_name} ****{obj.account_number[-4:]}"
    account_info.short_description = '账户信息'

    def mark_as_completed(self, request, queryset):
        """批量标记为已完成"""
        queryset.filter(status='pending').update(
            status='completed',
            processed_at=timezone.now()
        )
    mark_as_completed.short_description = '批量标记为已完成'

    def mark_as_failed(self, request, queryset):
        """批量标记为失败"""
        queryset.filter(status='pending').update(
            status='failed',
            processed_at=timezone.now()
        )
    mark_as_failed.short_description = '批量标记为失败'

    def action_buttons(self, obj):
        """生成操作按钮"""
        return format_html(
            '<a class="button" href="/admin/payments/djwithdrawal/{}/change/">编辑</a>&nbsp;'
            '<a class="button" href="/admin/payments/djwithdrawal/{}/delete/">删除</a>',
            obj.id, obj.id
        )
    action_buttons.short_description = '操作'

    # 添加自定义查询方法以处理可能的时区问题
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        # 过滤掉可能存在的无效日期时间值
        return qs.exclude(requested_at__isnull=True)


@admin.register(DjWalletTransaction)
class DjWalletTransactionAdmin(admin.ModelAdmin):
    """钱包交易流水管理"""
    list_display = (
        'id', 'wallet_link', 'chef_id', 'transaction_type',
        'amount', 'transaction_id', 'related_info', 'created_at', 'action_buttons'  # 增加操作列
    )
    list_filter = ('transaction_type', 'created_at')
    search_fields = ('transaction_id', 'note', 'chef_id')
    # 移除或注释掉date_hierarchy以避免时区错误
    # date_hierarchy = 'created_at'
    readonly_fields = ('created_at',)

    def wallet_link(self, obj):
        """生成钱包链接"""
        return format_html(
            '<a href="/admin/payments/djchefwallet/{}/">{}</a>',
            obj.wallet.id,
            f"钱包({obj.wallet.chef.real_name})"
        )
    wallet_link.short_description = '关联钱包'

    def related_info(self, obj):
        """显示关联业务信息"""
        if obj.related_withdrawal:
            return format_html(
                '提现 <a href="/admin/payments/djwithdrawal/{}/">#{}</a>',
                obj.related_withdrawal.id,
                obj.related_withdrawal.id
            )
        elif obj.related_order:
            return format_html(
                '订单 <a href="/admin/orders/order/{}/">{}</a>',
                obj.related_order.id,
                obj.related_order.order_number
            )
        return '-'
    related_info.short_description = '关联业务'

    def action_buttons(self, obj):
        """生成操作按钮"""
        return format_html(
            '<a class="button" href="/admin/payments/djwallettransaction/{}/change/">编辑</a>&nbsp;'
            '<a class="button" href="/admin/payments/djwallettransaction/{}/delete/">删除</a>',
            obj.id, obj.id
        )
    action_buttons.short_description = '操作'

    # 添加自定义查询方法以处理可能的时区问题
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        # 过滤掉可能存在的无效日期时间值
        return qs.exclude(created_at__isnull=True)